package com.jackrain.clouddata.oms.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.clouddata.sys.sender.BackSender;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.query.QueryEngine;
import com.sun.tools.corba.se.idl.constExpr.Times;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Set;

import static com.jackrain.clouddata.oms.util.KeyValueUtils.keyAppend;
import static com.jackrain.clouddata.oms.util.KeyValueUtils.valueAppend;

/**
 * Created by ZCY on 2017/8/19.
 */
@RestController
public class UploadStore {

    //接受烧卖发送来的盘点数据
    @RequestMapping(path = "/api/oms/uploadstore", method = RequestMethod.POST)
    public JSONObject Uploadfastore(HttpServletRequest request) throws Exception {
        ValueHolder vh = new ValueHolder();

        String tag = request.getHeader("tag");
        if (tag == null) {
            throw new NDSException("TAG为空!");
        }
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql, new Object[]{tag});
        if (clientJson == null) {
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        String params = TypeUtils.castToString(request.getParameter("params"));

        JSONObject paramobj = new JSONObject(true);
        paramobj = JSON.parseObject(params, new Feature[]{Feature.OrderedField});
        JSONArray fastorageary = paramobj.getJSONArray("fastorageitem");
        if (fastorageary.size() > 0) {
            vh = ApplicationContextHandle.getBean(UploadStore.class).inserttable(fastorageary, clientId, tag);
//            vh = inserttable(fastorageary, clientId, tag);
            return vh.toJSONObject();
        } else {
            vh.put("code", -1);
            vh.put("message", "库存消息为空或丢失");
        }
        return vh.toJSONObject();
    }

    @Transactional
    public ValueHolder inserttable(JSONArray fastorageary, Long clientId, String tag) {
        ValueHolder vh = new ValueHolder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");


        Timestamp current = new Timestamp(System.currentTimeMillis());
        String strcurrent = sdf.format(current);

        JSONArray Valueary = new JSONArray();
        Integer m = 0;
//        if (fastorageary.size() > 0) {
        String STORENAME = fastorageary.getJSONObject(0).getString("STORENAME");
        for (int i = 0; i < fastorageary.size(); i++) {
            JSONObject storageobj = new JSONObject(true);
            storageobj = fastorageary.getJSONObject(i);
            storageobj.remove("STORENAME");
            storageobj.remove("STATUS");
            storageobj.put("AD_CLIENT_ID", clientId);
            for (int o = 0; o < storageobj.keySet().size(); o++) {
                String key = (String) storageobj.keySet().toArray()[o];
                String value = storageobj.getString(key);
//                if (null == value) {
//                    storageobj.put(key, "");
//                }
                if (key.contains("DATE")) {
                    storageobj.put(key, storageobj.getTimestamp(key));
                }
            }
            storageobj.put("MODIFIEDDATE", current);
            storageobj.put("BATCH", strcurrent);
            storageobj.put("ID", Tools.getSequence("FA_STORAGEITEM"));
            Valueary.set(m++, storageobj);


        }
        if (Valueary.size() > 0) {
            JSONObject fastoragejsonobj = Valueary.getJSONObject(0);
            JSONObject mainobj = (JSONObject) fastoragejsonobj.clone();
            JSONObject maintable = new JSONObject(true);
            maintable = JSONObject.parseObject(mainobj.toString(), new Feature[]{Feature.OrderedField});
            maintable.remove("PRONO");
            maintable.remove("PROVALUE");
            maintable.remove("PRONAME");
            maintable.remove("SKUNO");
            maintable.remove("QTY");
            maintable.remove("QTYBEG");
            maintable.put("STORENAME", STORENAME);
            maintable.put("STATUS", 2);
            maintable.put("CREATIONDATE", current);
            maintable.put("MODIFIEDDATE", current);
            maintable.put("BILLDATE", current);
            maintable.put("ID", Tools.getSequence("FA_STORAGE"));
            StringBuffer hubstorage = new StringBuffer();
            hubstorage.append("INSERT INTO FA_STORAGE (" + keyAppend(maintable.keySet()) + ") VALUES(").append(valueAppend(maintable.size())).append(")");
            String fastorageintsql = hubstorage.toString();
            for (int j = 0; j < maintable.keySet().size(); j++) {
                String key = (String) maintable.keySet().toArray()[j];
                String value = maintable.getString(key);
                if (value == null) {
                    maintable.remove(key);
                    fastorageintsql = fastorageintsql.replace(key + ",", "");
                }
            }

            Integer resultmain = QueryEngine.getInstance().executeUpdate(fastorageintsql, maintable.values().toArray());
            if (resultmain > 0) {
                StringBuffer sbu = new StringBuffer();
                sbu.append("INSERT INTO FA_STORAGEITEM (" + keyAppend(Valueary.getJSONObject(0).keySet()) + ") VALUES(").append(valueAppend(Valueary.getJSONObject(0).size())).append(")");
                QueryEngine.getInstance().executeBatchUpdate(sbu.toString(), Valueary);
                vh.put("code", 0);
                vh.put("message", "库存数据插入成功");
                BackSender.send("OMS_FA_STOREAGE_BACK", tag, clientId.toString(), maintable.getString("BATCH"));
            } else {
                vh.put("code", -1);
                vh.put("message", "库存主表插入失败");
            }

        }
        return vh;
    }


}